﻿/***************************************************
 * File name: WscAuthorizeAttribute.cs 
 * Author: Team A
 * Change Log: Please see SVN repository: http://test-project-drew1.googlecode.com/svn/trunk/
 * Date: December 2013
 * Description: See <summary> tab below
 * *************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using security= System.Web.Security;
using WebMatrix.WebData;
using WSCeCommerceWeb.Filters;
using System.Web.Routing;

namespace WSCeCommerceWeb.Helpers
{
    /// <summary>
    /// Custom attribute that checks to see if a use is in the desired role.If the user is notin the role they are
    /// taken to a permission denied page.
    /// </summary>
    [InitializeSimpleMembership]

    public class WscAuthorizeAttribute : AuthorizeAttribute
    {
        public const char ROLES_SEPARATOR = ',';

        public WscAuthorizeAttribute()
        {
            this.CheckManage = false;
        }

        public bool CheckManage { get; set; }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            //If the user is not logged in the take them to the logon page
            if (filterContext.HttpContext.User.Identity == null || !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +
                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));

                return;
            }

            bool allow = false;

            //Verify the user is in the desired roles
            if (!String.IsNullOrWhiteSpace(this.Roles))
            {
                String[] roles = this.Roles.Split(ROLES_SEPARATOR);

                //Determine if the current user is in one of the desired roles
                allow = roles.Any(role => security.Roles.IsUserInRole(WebSecurity.CurrentUserName, role));
            }

            //If the CheckManage flag is set then check if the current user can manage
            allow |= CheckManage && SecurityHelper.AlllowManage();

            // If the user is not allowed than return not authorized.
            if (!allow)
            {
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.Result = new RedirectToRouteResult(
                                 new RouteValueDictionary {
                               { "controller", "Account" },    
                               { "action", "Denied" }                                       
                               });

            }
        }

    }
}
  